/** @odoo-module **/
/** Author      :    wsxzy98@outlook.com**/
/** Date        :    2025/06/8 15:41:01**/

import { patch } from "@web/core/utils/patch";
import { Chatter } from "@mail/chatter/web_portal/chatter";

patch(Chatter.prototype, {
    setup(...args) {
        super.setup(...args);
        setTimeout(() => {
            // ====== 参数 ======
            const MIN_WIDTH = 380;
            const MAX_WIDTH = 800;
            const DEFAULT_WIDTH = 380;

            // 1. 查找主chatter容器
            let chatterEl = document.querySelector('.o-mail-ChatterContainer, .oe_chatter, .o_ChatterContainer');
            if (!chatterEl) return;
            let stickyTop = chatterEl.querySelector('.o-mail-Chatter-top');
            let topbar = stickyTop ? stickyTop.querySelector('.o-mail-Chatter-topbar') : null;
            if (!topbar || topbar.querySelector('.chatter-toggle-btn')) return;

            // 2. 定位“活动”按钮，插在其右侧，支持中文/英文
            let actionBtns = topbar.querySelectorAll('button');
            let afterNode = null;
            for (let btn of actionBtns) {
                let txt = btn.textContent.trim();
                if (txt.includes('活动') || txt.toLowerCase().includes('activities')) {
                    afterNode = btn;
                    break;
                }
            }
            if (!afterNode && actionBtns.length >= 3) afterNode = actionBtns[2];

            // 3. 创建Odoo风格按钮
            const btn = document.createElement('button');
            btn.className = 'chatter-toggle-btn btn btn-link o-mail-Chatter-search border-0 bg-transparent p-0';
            btn.innerHTML = '<span style="font-size:20px;">⇔</span>';
            btn.title = '收起/展开聊天区';
            btn.style.marginLeft = '6px';
            btn.style.verticalAlign = 'middle';

            if (afterNode && afterNode.nextSibling) {
                topbar.insertBefore(btn, afterNode.nextSibling);
            } else {
                topbar.appendChild(btn);
            }

            // 4. 拖拽拉手
            let resizer = chatterEl.querySelector('.chatter-resizer');
            if (!resizer) {
                resizer = document.createElement("div");
                resizer.className = "chatter-resizer";
                resizer.style.width = "7px";
                resizer.style.height = "100%";
                resizer.style.position = "absolute";
                resizer.style.left = "0";
                resizer.style.top = "0";
                resizer.style.cursor = "ew-resize";
                resizer.style.background = "rgba(0,0,0,0.13)";
                resizer.style.zIndex = "100";
                resizer.style.transition = "background 0.2s";
                resizer.onmouseenter = () => resizer.style.background = "rgba(255,140,0,0.25)";
                resizer.onmouseleave = () => resizer.style.background = "rgba(0,0,0,0.13)";
                chatterEl.style.position = "relative";
                chatterEl.insertBefore(resizer, chatterEl.firstChild);
            }

            let lastRememberedWidth = null;

            // 5. 伸缩逻辑（与拖拽保持一致，收缩就是MIN_WIDTH）
            btn.onclick = function () {
                const isCollapsed = (parseInt(chatterEl.style.width) <= MIN_WIDTH + 2); // 容忍2px
                if (isCollapsed) {
                    let restore = lastRememberedWidth || chatterEl.dataset.oldwidth || DEFAULT_WIDTH;
                    if (parseInt(restore) > MAX_WIDTH || parseInt(restore) < MIN_WIDTH) restore = DEFAULT_WIDTH;
                    chatterEl.style.width = restore + "px";
                    chatterEl.style.minWidth = "";
                    chatterEl.style.maxWidth = "";
                    chatterEl.style.overflow = "auto";
                    chatterEl.style.flex = "none";
                } else {
                    if (!lastRememberedWidth) {
                        lastRememberedWidth = chatterEl.offsetWidth;
                        chatterEl.dataset.oldwidth = lastRememberedWidth;
                    }
                    chatterEl.style.width = MIN_WIDTH + "px";
                    chatterEl.style.minWidth = MIN_WIDTH + "px";
                    chatterEl.style.maxWidth = MIN_WIDTH + "px";
                    chatterEl.style.overflow = "hidden";
                    chatterEl.style.flex = "none";
                }
            };

            // 6. 拖拽逻辑（与按钮收缩一致，动态绑定监听器避免重复）
            resizer.onmousedown = function (e) {
                e.preventDefault();
                let nowWidth = chatterEl.offsetWidth;
                chatterEl.style.width = nowWidth + "px";
                chatterEl.style.minWidth = "";
                chatterEl.style.maxWidth = "";
                chatterEl.style.flex = "none";
                let dragStartX = e.clientX;
                let dragStartWidth = nowWidth;

                function mouseMoveHandler(moveEvent) {
                    let delta = moveEvent.clientX - dragStartX;
                    let newWidth = dragStartWidth - delta;
                    if (newWidth < MIN_WIDTH) newWidth = MIN_WIDTH;
                    if (newWidth > MAX_WIDTH) newWidth = MAX_WIDTH;
                    chatterEl.style.width = newWidth + "px";
                    lastRememberedWidth = newWidth;
                    chatterEl.dataset.oldwidth = newWidth;
                }
                function mouseUpHandler() {
                    document.removeEventListener('mousemove', mouseMoveHandler);
                    document.removeEventListener('mouseup', mouseUpHandler);
                    document.body.style.userSelect = "";
                }
                document.addEventListener('mousemove', mouseMoveHandler);
                document.addEventListener('mouseup', mouseUpHandler);
                document.body.style.userSelect = "none";
            };
        }, 800);
    }
});
